package com.pt25.base.dep.redis.aspect;

import com.pt25.base.dep.redis.RedisService;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class ClearCacheAspect extends BaseCacheAspect {
    @Resource
    private RedisService redisService;

    @Around("@annotation(com.pt25.base.dep.redis.aspect.ClearCache)")
    public Object clearCache(ProceedingJoinPoint pjp) throws Throwable {
        Method method = getMethod(pjp);
        //1、获取注解
        ClearCache clearCache = method.getAnnotation(ClearCache.class);
        //2、获取缓存key
        String dataCacheKey = getDataCacheKey(pjp, method, clearCache.cacheKey(), clearCache.value().getName());
        //3、清理缓存
        if (null != dataCacheKey) {
            RedissonClient redissonClient = redisService.getRedissonClient(clearCache.redisName());
            redissonClient.getBucket(dataCacheKey, new StringCodec()).delete();
        }
        return pjp.proceed();
    }
}
